//
//  PersonInfoViewController.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/9.
//

#import "PersonCenterViewController.h"
#import "PersonHeaderView.h"
#import "PersonFooterView.h"
#import "PersonCenterCell.h"
#import "RenYuanEduitVC.h"
#import "MoRenPersonVC.h"
#import "RenYuanGuanLiVC.h"
#import "LoginPageViewController.h"
#import "SuoShuQiYeViewController.h"
#import "AboutUSViewController.h"
#import "QuanXianModel.h"
#import "LXBelongingCompanyViewController.h"

@interface PersonCenterViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView       *tableView;
@property (nonatomic,strong) PersonHeaderView  *infoView;
@property (nonatomic,strong) NSMutableArray    *dataSource;
@property (nonatomic,strong) NSMutableArray    *iconArray;
@property (nonatomic,strong) NSMutableArray    *quanXianArray;
@property (nonatomic,strong) QuanXianSmallModel *renYuanModel;
@property (nonatomic,strong) YLUserInfo *info;

@end

@implementation PersonCenterViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self layoutCustomNav:self.view title:@"个人中心"];
     self.info = [YLUserMgr fetchUser];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.quanXianArray = [NSMutableArray array];
    self.iconArray = [NSMutableArray arrayWithArray:@[@"qiYe",@"renYuan",@"moRen",@"guanYu",@"renYuan"]];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, ScreenWidth, B_HEIGHT - LL_StatusBarAndNavigationBarHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = White_Color;
    self.tableView.separatorColor = White_Color;
   [self.view addSubview:self.tableView];
    if(@available(iOS 11.0, *)){
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.tableView registerNib:[UINib nibWithNibName:[PersonCenterCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[PersonCenterCell reuseIdentifier]];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    CGRect frame = CGRectMake(0, 0, 0, 0.1);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];
    [self getQuanXianDataSource];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonCenterCell *cell = [self.tableView dequeueReusableCellWithIdentifier:[PersonCenterCell reuseIdentifier]];
    if (!cell){
        cell = [[PersonCenterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[PersonCenterCell reuseIdentifier]];
              }
    cell.nameLb.text = self.dataSource[indexPath.row];
    cell.iconImage.image = [UIImage imageNamed:self.iconArray[indexPath.row]];
    if (indexPath.row == 0 || indexPath.row == 1) {
        cell.signLb.hidden = NO;
        if (indexPath.row == 0){
            if ([NSString isNUllString:self.info.enterpriseName]) {
                cell.signLb.text = @"未加入";
            } else {
                cell.signLb.text = self.info.enterpriseName;
            }
        } else {
            if (self.renYuanModel) {
                if ([NSString isNUllString:self.renYuanModel.roleName]){
                    cell.signLb.text = @"未设置";
                } else {
                    cell.signLb.text = self.renYuanModel.roleName;
                }
            } else {
                cell.signLb.text = @"";
            }
        }
    } else {
        cell.signLb.hidden = YES;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [PersonCenterCell cellHeight];
 }

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 70)];
    self.infoView = [PersonHeaderView shareInstance];
    self.infoView.frame = CGRectMake(0, 0, ScreenWidth, 70);
    [headerView addSubview:self.infoView];
    [self.infoView.headerImageButton setBackgroundImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HTTP_URL,self.info.avatar]] placeholderImage:Image(@"header_default")];
//    if ([NSString isNUllString:self.info.roleName]) {  //职位
//        self.infoView.zhiWeiLb.text = @"未设置";
//    } else {
        self.infoView.zhiWeiLb.text = [[MSStorageUtils shareInstance] userDefaultGet:COMPANY_ROLE_NAME];
//    }
    
    self.infoView.nameLb.text = self.info.realName;//姓名
    [self.infoView.settingButton whenTapped:^{
        //设置
        RenYuanEduitVC *VC = [[RenYuanEduitVC alloc] init];
        [self pushToNextController:VC];
    }];
    return headerView;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 70)];
    PersonFooterView *footer = [PersonFooterView shareInstance];
    footer.frame=CGRectMake(0, 0, ScreenWidth, 70);
    [footer.checkOutButton whenTapped:^{
        [self alertCheck];
    }];
    [footerView addSubview:footer];
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 70;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 70;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
        {//所属企业
            if ([NSString isNUllString:self.info.enterpriseName]) {
//                SuoShuQiYeViewController  *  VC =[[SuoShuQiYeViewController alloc] init];
//                VC.isFromeLogin=NO;
//                [self pushToNextController:VC];
            } else {
                LXBelongingCompanyViewController *vc  = [[LXBelongingCompanyViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                
            }
            
        }
        break;
        case 1:
        {//人员管理
            if (self.renYuanModel){
                RenYuanGuanLiVC *VC = [[RenYuanGuanLiVC alloc] init];
                [self pushToNextController:VC];
            } else {
                //默认联系人
                MoRenPersonVC *VC = [[MoRenPersonVC alloc] init];
                [self pushToNextController:VC];
            }
          
        }
        break;
        case 2:
        {//默认联系人
            if (self.renYuanModel){
                 MoRenPersonVC *VC = [[MoRenPersonVC alloc] init];
                [self pushToNextController:VC];
            } else {
                //关于
                AboutUSViewController *VC = [[AboutUSViewController alloc] init];
               [self pushToNextController:VC];
            }
        }
        break;
        case 3:
        {//关于
             AboutUSViewController *VC = [[AboutUSViewController alloc] init];
            [self pushToNextController:VC];
        }
        case 4:
        {
            [self removeAccount];
        }
        break;
        default:
        break;
    }
}

-(void)alertCheck{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定退出登录?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        [self checkOut];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
}
-(void)removeAccount{
    
    [Tool showAlertTitle:@"您确定要注销此账号吗?" msg:nil cancelTitle:@"取消" commitBtnTitle:@"注销" cancelHandlerBlock:^{
        
    } commitHandlerBlock:^{
        
        
        NSString *url = [NSString stringWithFormat:@"%@%@",DOMAIN_URL,GET_GetRemoveAccount];

        [MSNetworkManager getRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
            if(isSuccess){
                showAlert(@"账号注销成功");
                [self checkOut];
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            
        } withShowHud:NO];
        
        
    } onVC:self];
    
    
}
-(void)checkOut{
  
    [[MSStorageUtils shareInstance] userDefaultSave:@"NO" withKey:USER_DEFAULT_KEY_MEMBER_IsLogin];
    [[SDWebImageDownloader sharedDownloader] cancelAllDownloads];
    [[YTKNetworkAgent sharedAgent] cancelAllRequests];
    [SSKeyChainMgr delLoginToken];
    [YLUserMgr deleteUser];
    LoginPageViewController *pageVC = [[LoginPageViewController  alloc] init];
    UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:pageVC];
    UIWindow  *mainWindow = [BaseViewController getCurrentWindow];
    [mainWindow setRootViewController:navigationVC];
    
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
    } seq:1];
    
    showAlert(@"退出成功");
  
}

-(void)getQuanXianDataSource{
    
    
    NSString *url = [NSString stringWithFormat:@"%@%@",DOMAIN_URL,USER_URL];

    [MSNetworkManager getRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if(isSuccess){
            NSArray *cacheArray = resonseObj[@"roleList"];
            NSMutableArray *xuArray = [QuanXianSmallModel mj_objectArrayWithKeyValuesArray:cacheArray];
            for(QuanXianSmallModel *model in xuArray){
                if ([model.roleCode isEqualToString:@"enter_admin"]){
                    self.renYuanModel = model;
                } else {
                    self.renYuanModel = model;
                    [USER_DEFAULT setObject:@"EDITQYDATA" forKey:EduitString_key];
                    [USER_DEFAULT synchronize];
                }
            }
            if (self.renYuanModel){
                self.dataSource = [NSMutableArray arrayWithArray:@[@"所属企业",@"人员管理",@"默认联系人",@"关于",@"注销账号"]];
            } else {
                self.dataSource = [NSMutableArray arrayWithArray:@[@"所属企业",@"默认联系人",@"关于",@"注销账号"]];
            }
            [self.tableView reloadData];
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        
    } withShowHud:NO];
    

    
}

@end
